<?php
/***************************************************************
*  Copyright notice
*  (c) 2009, jianyuzhu@gmail.com
*  All rights reserved
*  This script is part of the PPEMI project.
***************************************************************/

class LibImageText {
	//text
	var $text = '';
	
	//
	var $font_path = 'images/fonts/';
	var $font_list = array(
        'Antykwa'  => array('spacing' => -3, 'minSize' => 27, 'maxSize' => 40, 'font' => 'AntykwaBold.ttf'),
        'Candice'  => array('spacing' =>-1.5,'minSize' => 28, 'maxSize' => 31, 'font' => 'Candice.ttf'),
        'DingDong' => array('spacing' => -2, 'minSize' => 24, 'maxSize' => 30, 'font' => 'Ding-DongDaddyO.ttf'),
        'Duality'  => array('spacing' => -2, 'minSize' => 30, 'maxSize' => 38, 'font' => 'Duality.ttf'),
        'Heineken' => array('spacing' => -2, 'minSize' => 24, 'maxSize' => 34, 'font' => 'Heineken.ttf'),
        'Jura'     => array('spacing' => -2, 'minSize' => 28, 'maxSize' => 32, 'font' => 'Jura.ttf'),
        'StayPuft' => array('spacing' =>-1.5,'minSize' => 28, 'maxSize' => 32, 'font' => 'StayPuft.ttf'),
        'Times'    => array('spacing' => -2, 'minSize' => 28, 'maxSize' => 34, 'font' => 'TimesNewRomanBold.ttf'),
        'VeraSans' => array('spacing' => -1, 'minSize' => 20, 'maxSize' => 28, 'font' => 'VeraSansBold.ttf'),
        'HANDGOTB' => array('spacing' => -1, 'minSize' => 20, 'maxSize' => 28, 'font' => 'HANDGOTB.TTF'),
    );
	var $font_name = 'HANDGOTB';
	
	//Background color
	var $backgroundColor = array(248, 248, 248);
	//Foreground color
	var $foregroundColor = array(0, 0, 0);
    //Foreground colors
    var $colors = array(
        //array(27,78,181), // blue
        //array(22,163,35), // green
        //array(214,36,7),  // red
		array(0,0,0),	  // black
		//array(255,255,255),//white
    );
	//Shadow Color
	var $shadowColor = null; //array(0, 0, 0);
	
    //Min word length (for non-dictionary random text generation)
    var $minWordLength = 5;

    /**
     * Max word length (for non-dictionary random text generation)
     * 
     * Used for dictionary words indicating the word-length
     * for font-size modification purposes
     */
    var $maxWordLength = 30;
	
	//
	var $width = 480;
	var $height = 50;
	var $imageFormat = 'jpg';
	
	//
	var $save_path = 'images/texts/';
	var $save_type = '';
	var $save_image = false;
	var $save_filename = '';
	var $save_name = '';
	
    //Internal image size factor (for better image quality)
	//1: low, 2: medium, 3: high
    var $scale = 1;
	
	//
	var $im;
	
	//constructor
	function LibImageText() {
		
	}
	
	//methods
	function image() {
		$text = $this->text;
		//
        $this->_image_allocate();
		if( $this->font_name != '' && isset($this->font_list[$this->font_name]) ) {
			$fontcfg = $this->font_list[$this->font_name];
		} else {
        	$fontcfg  = $this->font_list[array_rand($this->font_list)];
		}
        $this->_image_text_wh($text, $fontcfg);

        if( $this->blur && function_exists('imagefilter') ) {
            imagefilter($this->im, IMG_FILTER_GAUSSIAN_BLUR);
        }
        $this->_image_reduce();
		
		if( $this->save_image == true ) {
        	$this->_image_save();
		} else {
        	$this->_image_write();
		}
        $this->_image_cleanup();
	}
	
	//
    function _image_allocate() {
		// Cleanup
		if (!empty($this->im)) {
			imagedestroy($this->im);
        }
		
		$this->im = imagecreatetruecolor($this->width*$this->scale, $this->height*$this->scale);

        // Background color
        $this->GdBgColor = imagecolorallocate($this->im,
            $this->backgroundColor[0],
            $this->backgroundColor[1],
            $this->backgroundColor[2]
        );
        imagefilledrectangle($this->im, 0, 0, $this->width*$this->scale, $this->height*$this->scale, $this->GdBgColor);

        // Foreground color
        $color           = $this->colors[mt_rand(0, sizeof($this->colors)-1)];
        $this->GdFgColor = imagecolorallocate($this->im, $color[0], $color[1], $color[2]);

        // Shadow color
        if (!empty($this->shadowColor) && is_array($this->shadowColor) && sizeof($this->shadowColor) >= 3) {
            $this->GdShadowColor = imagecolorallocate($this->im,
                $this->shadowColor[0],
                $this->shadowColor[1],
                $this->shadowColor[2]
            );
        }
    }
	
	//
	function _image_text($text, $fontcfg = array()) {
		if (empty($fontcfg)) {
			// Select the font configuration
			$fontcfg  = $this->font_list[array_rand($this->font_list)];
		}
		
		// Full path of font file
		$fontfile = $this->font_path . $fontcfg['font'];
		
		//Increase font-size for shortest words: 9% for each glyp missing
		$lettersMissing = $this->maxWordLength-strlen($text);
		$fontSizefactor = 1+($lettersMissing*0.09);
		
		// Text generation (char by char)
		$x      = 20*$this->scale;
		$y      = round(($this->height*27/40)*$this->scale);
		$length = strlen($text);
		for ($i=0; $i<$length; $i++) {
			//$degree   = rand($this->maxRotation*-1, $this->maxRotation);
			//$fontsize = rand($fontcfg['minSize'], $fontcfg['maxSize'])*$this->scale*$fontSizefactor;
			$degree = 0;
			$fontsize = $fontcfg['maxSize']*$this->scale*$fontSizefactor;
			$letter   = substr($text, $i, 1);
			
			if( $this->shadowColor ) {
				$coords = imagettftext($this->im, $fontsize, $degree,
								$x+$this->scale, $y+$this->scale,
								$this->GdShadowColor, $fontfile, $letter);
			}
			$coords = imagettftext($this->im, $fontsize, $degree,
								$x, $y,
								$this->GdFgColor, $fontfile, $letter);
			$x += ($coords[2]-$x) + ($fontcfg['spacing']*$this->scale);
		}
	}
	
	//
	function _image_texts($text, $fontcfg = array()) {
		if (empty($fontcfg)) {
			// Select the font configuration
			$fontcfg  = $this->font_list[array_rand($this->font_list)];
		}
		
		// Full path of font file
		$fontfile = $this->font_path . $fontcfg['font'];
		
		//Increase font-size for shortest words: 9% for each glyp missing
		$lettersMissing = $this->maxWordLength-strlen($text);
		$fontSizefactor = 1+($lettersMissing*0.09);
		
		// Text generation (char by char)
		$x      = 20*$this->scale;
		$y      = round(($this->height*27/40)*$this->scale);
		$degree = 0;
		$fontsize = $fontcfg['maxSize']*$this->scale*$fontSizefactor;
		
		//$fontsize = 20;
		
		//
		if( $this->shadowColor ) {
			$coords = imagettftext($this->im, $fontsize, $degree,
							$x+$this->scale, $y+$this->scale,
							$this->GdShadowColor, $fontfile, $text);
		}
		$coords = imagettftext($this->im, $fontsize, $degree,
							$x, $y,
							$this->GdFgColor, $fontfile, $text);
	}
	
	//
	function _image_text_wh($text, $fontcfg = array()) {
		if (empty($fontcfg)) {
			// Select the font configuration
			$fontcfg  = $this->font_list[array_rand($this->font_list)];
		}
		
		// Full path of font file
		$fontfile = $this->font_path . $fontcfg['font'];
		
		$text_size = 20;
		$text_angle = 0;
		$text_box = imagettfbbox($text_size, $text_angle, $fontfile, $text);
		$text_w = $text_box['2'] - $text_box['0'];
		$text_h = $text_box['3'] - $text_box['5'];
		//$text_x = ceil(($this->width - $text_w)/2);
		//$text_y = $text_h+10;
		$text_x = 10;
		$text_y = $text_h + ceil(($this->height - $text_h)/2);
		
		imagettftext($this->im, $text_size, $text_angle, $text_x, $text_y, $this->GdFgColor, $fontfile, $text);
	}
	
	//
	function _image_reduce() {
		$imResampled = imagecreatetruecolor($this->width, $this->height);
		imagecopyresampled($imResampled, $this->im,
			0, 0, 0, 0,
			$this->width, $this->height,
			$this->width*$this->scale, $this->height*$this->scale
		);
		imagedestroy($this->im);
		$this->im = $imResampled;
	}
	
	//
	function _image_write() {
		if( $this->imageFormat == 'png' && function_exists('imagepng') ) {
			header("Content-type: image/png");
			imagepng($this->im);
		} else {
			header("Content-type: image/jpeg");
			imagejpeg($this->im, null, 80);
		}
	}
	
	//
	function _image_save() {
		$file = $this->_image_file();
		if( $this->imageFormat == 'png' && function_exists('imagepng') ) {
			imagepng($this->im, $file);
		} else {
			imagejpeg($this->im, $file, 80);
		}
	}
	
	//
	function _image_cleanup() {
		imagedestroy($this->im);
		$this->im = NULL;
	}
	
	//
	function _image_file() {
		$filename = $this->_image_filename();
		$this->save_filename = $filename;
		
		return $this->save_path . $filename;
	}
	
	//
	function _image_filename() {
		$filename = $this->_generate_filepath() . $this->_generate_filename();
		if( file_exists($this->save_path . $filename) ) {
			return $this->_image_filename();
		}
		
		return $filename;
	}
	
	//
	function _random() {
		return util_create_random_value('8', 'mixed');
	}
	
	function _generate_filename() {
		if( $this->imageFormat == 'png' && function_exists('imagepng') ) {
			$extension = 'png';
		} else {
			$extension = 'jpg';
		}
		
		if( $this->save_name != '' ) {
			return $this->save_name . '.' . $extension;
		}
		
		return substr(md5(time()), 0, 16) . '_' . $this->_random() . '.' . $extension;
	}
	
	function _generate_filepath() {
		if( !is_dir($this->save_path) ) {
			die("ERROR DIR");
		}
		$save_subdir = '';
		if( $this->save_type == 'month' ) {
			$save_subdir = strftime("%Y%m", time());
		} elseif( $this->save_type == 'day' ) {
			$save_subdir = strftime("%Y%m%d", time());
		} elseif( $this->save_type == 'random' ) {
			$save_subdir = substr(md5(strftime("%Y%m", time())), 0, 6);
		}
		$save_subdir = trim($save_subdir);
		if( strlen($save_subdir) > 0 ) {
			if( !is_dir($this->save_path . $save_subdir . '/') ) {
				@mkdir($this->save_path . $save_subdir . '/');
			}
			$filepath = $save_subdir . '/';
			if( !is_dir($this->save_path . $filepath) ) {
				die("ERROR DIRS");
			}
		} else {
			$filepath = $save_subdir;
		}
		
		return $filepath;
	}
}
//
?>